//
//  ZBPullDownRefreshView.m
//  555Lottery
//
//  Created by zhoubo on 2017/7/6.
//  Copyright © 2017年 zhoubo. All rights reserved.
//

#import "ZBPullDownRefreshView.h"
#import "Head.h"
#import "Masonry.h"


const CGFloat Height = 60;

@interface ZBPullDownRefreshView ()



@property (nonatomic,strong) UIScrollView* superScrollView;

@property (nonatomic,strong) UIImageView* arrowView;
@property (nonatomic,strong) UIImageView* fhlView;
@property (nonatomic,strong) UILabel* messagelbl;

@property (nonatomic,assign) BOOL  isFromRefreshToNormal;



@end

@implementation ZBPullDownRefreshView


-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self setupUI];
    }
    return self;
}

-(void)setupUI
{
    
    self.frame = CGRectMake(0, -Height,SWidth , Height);
    self.status = Normal;
    
    [self addSubview:self.arrowView];
    [self addSubview:self.fhlView];
    [self addSubview:self.messagelbl];
    
    //添加约束
    [self.fhlView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self).offset(-30);
        make.centerY.equalTo(self);
        
        
    }];
    
    [self.arrowView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.fhlView);
    }];
    
    [self.messagelbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.fhlView.mas_trailing).offset(10);
        make.centerY.equalTo(self.fhlView);
    }];
}


//当控件被添加到浮空家你的时候会调用这个方法  这个刷新view的父控件就是tableview
-(void)willMoveToSuperview:(UIView *)newSuperview
{
    [super willMoveToSuperview:newSuperview];
    // 判断父控件是Scrollview或者其子类
    // 如果父控件是scrollview或者其子类
    if ([newSuperview isKindOfClass:[UIScrollView class]]) {
        self.superScrollView = (UIScrollView*)newSuperview;
        
        // 使用kvo来监听父控件(tableivew)滚动
        [self.superScrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
    }
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
//    NSLog(@"滚动了:%lf",self.superScrollView.contentOffset.y);

    // 滚动的offset.y > -60  正常状态  滚动了offset.y<-60 即将刷新状态
    CGFloat offsety = self.superScrollView.contentOffset.y;
    
    // ®®®因为系统第一次加载tableivew的时候 系统会自动调整他的offset 也会调用这个方法  所以我们要过滤掉系统的  if dragging的时候才表示用户的拖拽
    
    if (self.superScrollView.dragging) {
        if (offsety > -Height && self.status == PullToRefresh) {
            
            //需要切换状态  从pulltoReresh状态切换到normal状态
            self.status = Normal;
//            NSLog(@"切换到normal");
            
            
        }
        else if(offsety < -Height && self.status == Normal)
        {
            self.status = PullToRefresh;
//            NSLog(@"切换到PullToRefresh");
        }
    }else  if (self.status == PullToRefresh)
    {
        // 如果是非拖动状态 并且status是即将刷新状态
        self.status = Refreshing;
//        NSLog(@"切换到Refreshing状态");
    }
}


-(void)setStatus:(RefreshStatus)status
{

    _status = status;
    self.fhlView.hidden = YES;
    self.arrowView.hidden = NO;
    if (status == Normal) {
        self.messagelbl.text = @"下拉刷新";
        
        if (self.isFromRefreshToNormal) {
            self.isFromRefreshToNormal = false;
            self.arrowView.transform = CGAffineTransformIdentity;

        }
        else
        {
            //箭头旋转
            [UIView animateWithDuration:0.2 animations:^{
                self.arrowView.transform = CGAffineTransformIdentity;
            }];
        }

        
        //tableview偏移自身的height
        [UIView animateWithDuration:0.5 animations:^{
            
            // ®®®®崩溃
            self.superScrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        }];
        
    }
    else if (status == PullToRefresh)
    {
        self.messagelbl.text = @"释放刷新";
        //箭头旋转
        [UIView animateWithDuration:0.2 animations:^{
            self.arrowView.transform = CGAffineTransformMakeRotation(M_PI);
        }];
    }
    else
    {
        self.fhlView.hidden = NO;
        self.arrowView.hidden = YES;
        self.messagelbl.text = @"正在刷新...";
        CABasicAnimation*animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
        animation.toValue = [NSNumber numberWithFloat:M_PI * 2];
        animation.repeatCount = MAXFLOAT;
        animation.duration = 1;
        animation.fillMode = kCAFillModeForwards;
        animation.removedOnCompletion = NO;
        [self.fhlView.layer addAnimation:animation forKey:@"rotationAnim"];
        
        //tableview偏移自身的height
        [UIView animateWithDuration:0.5 animations:^{
            self.superScrollView.contentInset = UIEdgeInsetsMake(Height, 0, 0, 0);
        }];
        
        
        // 刷新
        if (self.refreshBlock) {
            self.refreshBlock();
        }
        
    }
}


-(void)endrefresh
{
    self.isFromRefreshToNormal = YES;
//    CFTimeInterval pausedTime = [self.fhlView.layer convertTime:CACurrentMediaTime() fromLayer:nil];
//    self.fhlView.layer.speed               = 0.0;
//    self.fhlView.layer.timeOffset          = pausedTime;
    [self.fhlView.layer removeAnimationForKey:@"rotationAnim"];
    self.status = normal;
    
}

-(void)dealloc
{
    [self removeObserver:self forKeyPath:@"contentOffset"];
}




-(UIImageView *)arrowView
{
    if (_arrowView == nil) {
        _arrowView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"tableview_pull_refresh"]];
    }
    return _arrowView;
}

-(UIImageView *)fhlView
{
    if (_fhlView == nil) {
        _fhlView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"tableview_loading"]];
        
    }
    return _fhlView;
}

-(UILabel *)messagelbl
{
    if (_messagelbl == nil) {
        _messagelbl = [[UILabel alloc]init];
        [_messagelbl setFont:[UIFont systemFontOfSize:14]];
        [_messagelbl setTextColor:[UIColor darkGrayColor]];
        _messagelbl.text = @"下拉刷新";

        
    }
    return _messagelbl;
}


@end
